<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="110px">
      <el-form-item label="当事人名称" prop="partyName">
        <el-input
          v-model="queryParams.partyName"
          placeholder="请输入当事人名称"
          clearable
          :style="{ width: '220px' }"
          @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="立案号" prop="caseNo">
        <el-input
          v-model="queryParams.caseNo"
          placeholder="请输入立案号"
          clearable
          :style="{ width: '220px' }"
          @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="处罚决定书文号" prop="decisionsNo">
        <el-input
          v-model="queryParams.decisionsNo"
          placeholder="请输入处罚决定书文号"
          clearable
          :style="{ width: '220px' }"
          @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="审批状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择审批状态" :style="{ width: '220px' }">
          <el-option v-for="item in statusList" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="申请时间" prop="daterangeApplyTime">
        <el-date-picker
          clearable
          v-model="daterangeApplyTime"
          type="daterange"
          value-format="YYYY-MM-DD"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :style="{ width: '220px' }"></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb10">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['noticedemandapproval:noticedemandapproval:add']">
          新增
        </el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['noticedemandapproval:noticedemandapproval:edit']">
          修改
        </el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="delDis"
          @click="handleDelete"
          v-hasPermi="['noticedemandapproval:noticedemandapproval:remove']">
          删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          :disabled="multiple"
          @click="handleExport"
          v-hasPermi="['noticedemandapproval:noticedemandapproval:export']">
          导出
        </el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" :columns="columns" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="noticedemandapprovalList" border @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <template v-for="column in newColumns" :key="column.key">
        <el-table-column
          :label="column.label"
          :prop="column.key"
          :min-width="column.minWidth || ''"
          :width="column.width || ''"
          align="center">
          <template v-if="column.key === 'applyTime'" #default="scope">
            <span>{{ parseTime(scope.row.applyTime, '{y}-{m}-{d}') }}</span>
          </template>
          <template v-else-if="column.key === 'status'" #default="scope">
            <el-tag
              :type="
                scope.row.applyStatus === '1'
                  ? 'primary'
                  : scope.row.applyStatus === '2'
                  ? 'danger'
                  : scope.row.applyStatus === '3'
                  ? 'success'
                  : scope.row.applyStatus === '4'
                  ? 'info'
                  : scope.row.applyStatus === '5'
                  ? 'success'
                  : scope.row.applyStatus === '0'
                  ? 'info'
                  : 'danger'
              ">
              {{ statusList.find(item => item.value === scope.row.applyStatus)?.label || '--' }}
            </el-tag>
          </template>
        </el-table-column>
      </template>
      <el-table-column
        label="操作"
        width="240"
        :show-overflow-tooltip="false"
        fixed="right"
        align="center"
        class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="view"
            @click="handleUpdate(scope.row, 'view')"
            v-hasPermi="['noticedemandapproval:noticedemandapproval:query']">
            查看
          </el-button>
          <el-button
            v-if="Number(scope.row.status) <= 1"
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row, 'edit')"
            v-hasPermi="['noticedemandapproval:noticedemandapproval:edit']">
            修改
          </el-button>
          <el-button link type="primary" icon="view" @click="handlePreview(scope.row)">预览</el-button>
          <el-button link type="primary" icon="upload" @click="handleUpload(scope.row)">上传附件</el-button>
          <el-button
            v-if="Number(scope.row.status) <= 1"
            link
            type="danger"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['noticedemandapproval:noticedemandapproval:remove']">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改结案审批审批对话框 -->
    <el-dialog :title="title" v-model="open" width="1200px" append-to-body>
      <NoticedemandapprovalDetail
        v-if="open"
        ref="detailRef"
        :id="formId"
        :disabled="dialogType === 'view'"
        :isEdit="title !== '添加结案审批'"
        @handleSubmit="handleDetailSubmit" />
      <template #footer>
        <div class="dialog-footer">
          <el-button v-if="dialogType !== 'view'" @click="handleSubmit(1)">保存为草稿</el-button>
          <el-button v-if="dialogType !== 'view'" type="primary" @click="handleSubmit(2)">提交</el-button>
          <el-button :loading="preViewLoading" @click="handlePreview2">预览</el-button>
          <el-button v-if="Number(status) > 1" @click="handleFlowRecord">
            <svg-icon icon-class="liuzhuanjilu" />
            流转记录
          </el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 上传附件弹窗 -->
    <el-dialog title="上传附件" v-model="fileModal" width="1200px">
      <FileList v-if="fileModal" :fileUploadList="fileUploadList" />
      <template #footer>
        <div class="form-footer">
          <el-button type="primary" @click="handleUploadConfirm">保存</el-button>
          <el-button @click="() => (fileModal = false)">取消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 流转记录 -->
    <flow-record v-model:modelValue="circulationVisible" :flow-list="circulationList" />
  </div>
</template>

<script setup name="Noticedemandapproval">
import {
  caseclosureapprovalList,
  delCaseclosureapproval,
  caseclosureapprovalDetail,
  previewCaseclosureapproval,
  exportCaseclosureapproval,
  addCaseclosureapprovalFiles,
} from '@/api/caseClosed/index.js'
import NoticedemandapprovalDetail from './detail.vue'
import useDictStore from '@/store/modules/dict'
import FileList from '@/components/FileList/index.vue'
import { ElMessage } from 'element-plus'
import { downloadBlob } from '@/utils/download.js'
import { getTodoFlowRecord } from '@/api/workFlow/index'
import flowRecord from '@/components/flowRecord/index.vue'

const { statusBtnList, statusList } = useDictStore()

const { proxy } = getCurrentInstance()
const route = useRoute()

const query = route.query
if (query.formId) {
  // 案件检索跳转过来
  proxy.$nextTick(() => {
    setTimeout(() => {
      handleUpdate({ id: query.formId }, 'view')
    }, 100)
  })
}

const columns = ref([
  { key: 'caseNo', label: '立案号', visible: true, minWidth: '220' },
  { key: 'partyName', label: '当事人名称', visible: true, minWidth: '180' },
  { key: 'caseCause', label: '案由', visible: true, minWidth: '220' },
  { key: 'decisionsNo', label: '行政处罚决定书文号', visible: true, minWidth: '220' },
  { key: 'applyTime', label: '申请时间', visible: true, width: '160' },
  { key: 'status', label: '状态', visible: true, minWidth: '120' },
])

const newColumns = computed(() => columns.value.filter(column => column.visible))

const noticedemandapprovalList = ref([])
const open = ref(false)
const loading = ref(true)
const dialogType = ref('add')
const formId = ref(null)
const daterangeApplyTime = ref([])
const detailRef = ref()
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref('')

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    partyName: undefined,
    caseNo: undefined,
    decisionsNo: undefined,
    status: undefined,
  },
  rules: {
    caseId: [{ required: true, message: '立案登记ID不能为空', trigger: ['blur', 'change'] }],
    caseNo: [{ required: true, message: '立案号不能为空', trigger: ['blur', 'change'] }],
    decisionsId: [{ required: true, message: '行政处罚决定书ID不能为空', trigger: ['blur', 'change'] }],
    partyName: [{ required: true, message: '当事人名称不能为空', trigger: ['blur', 'change'] }],
    streetOfCompanyAddress: [{ required: true, message: '所属街道不能为空', trigger: ['blur', 'change'] }],
    address: [{ required: true, message: '地址不能为空', trigger: ['blur', 'change'] }],
    unifiedSocialCreditCode: [{ required: true, message: '统一社会信用代码不能为空', trigger: ['blur', 'change'] }],
    legalRepresentative: [{ required: true, message: '法定代表人不能为空', trigger: ['blur', 'change'] }],
    penaltyAmount: [{ required: true, message: '罚款金额不能为空', trigger: ['blur', 'change'] }],
    productionDate: [{ required: true, message: '制作日期不能为空', trigger: ['blur', 'change'] }],
    deliveryDate: [{ required: true, message: '送达日期不能为空', trigger: ['blur', 'change'] }],
    status: [{ required: true, message: '状态不能为空', trigger: 'change' }],
    createBy: [{ required: true, message: '创建人不能为空', trigger: ['blur', 'change'] }],
    updateBy: [{ required: true, message: '更新人不能为空', trigger: ['blur', 'change'] }],
  },
})

const { queryParams, form, rules } = toRefs(data)

/** 查询行政处罚强结案审批列表 */
function getList() {
  loading.value = true
  queryParams.value.params = {}
  if (null != daterangeApplyTime && '' != daterangeApplyTime) {
    queryParams.value.params['beginApplyTime'] = daterangeApplyTime.value[0]
    queryParams.value.params['endApplyTime'] = daterangeApplyTime.value[1]
  }
  caseclosureapprovalList(queryParams.value).then(response => {
    noticedemandapprovalList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  formId.value = ''
  status.value = ''
  instanceId.value = ''
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  daterangeApplyTime.value = []
  proxy.resetForm('queryRef')
  handleQuery()
}

const selectList = ref([])
// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  selectList.value = selection
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  dialogType.value = 'add'
  formId.value = null
  open.value = true
  title.value = '添加结案审批'
}
const status = ref('')
const instanceId = ref('')
/** 修改按钮操作 */
function handleUpdate(row, type = 'edit') {
  reset()
  const _id = row.id || ids.value
  dialogType.value = type
  status.value = row.status
  instanceId.value = row.procInsId
  formId.value = _id
  open.value = true
  title.value = type === 'view' ? '查看结案审批' : '修改结案审批'
}

// 预览
const previewRow = ref(null)
const handlePreview = async row => {
  loading.value = true
  previewRow.value = row
  const res = await previewCaseclosureapproval({ id: row.id })
  if (!!res.msg) {
    window.open(res.msg)
  } else {
    ElMessage.warning('预览文件不存在')
  }
  loading.value = false
}
/** 删除按钮操作 */
const delDis = computed(() => {
  return ids.value.length === 0 || selectList.value.some(item => item.status !== '1')
})
// 上传附件
const fileModal = ref(false)
const fileUploadList = ref([])
const rowId = ref('')
const handleUpload = async row => {
  rowId.value = row.id
  const res = await caseclosureapprovalDetail(row.id)
  fileUploadList.value = res.data.tcaseClosureApprovalFilesList || []
  fileModal.value = true
}
// 上传附件
const handleUploadConfirm = async () => {
  await addCaseclosureapprovalFiles({
    id: rowId.value,
    tcaseClosureApprovalFilesList: fileUploadList.value,
  })
  ElMessage.success('保存成功')
  fileModal.value = false
}

const preViewLoading = ref(false)
function handlePreview2() {
  preViewLoading.value = true
  detailRef.value?.handlePreview().then(res => {
    preViewLoading.value = false
  })
}

/** 提交按钮 */
function handleSubmit(type) {
  detailRef.value?.submitForm(type === 1 ? true : false)
}

/** 流转记录按钮操作 */
const circulationList = ref([])
const circulationVisible = ref(false)
async function handleFlowRecord() {
  const res = await getTodoFlowRecord({ instanceId: instanceId.value, order: '1' })
  const { data } = res
  circulationList.value = data
  circulationVisible.value = true
}

/** 处理detail组件提交结果 */
function handleDetailSubmit(result) {
  if (result) {
    open.value = false
    getList()
  }
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal
    .confirm('是否确定删除编号为"' + _ids + '"的数据项？')
    .then(function () {
      return delCaseclosureapproval(_ids)
    })
    .then(() => {
      getList()
      proxy.$modal.msgSuccess('删除成功')
    })
    .catch(() => {})
}

// 附件相关方法已移至detail组件中

/** 导出按钮操作 */
async function handleExport() {
  const _ids = ids.value
  const res = await exportCaseclosureapproval(_ids)
  downloadBlob(res)
}

getList()
</script>
